/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.lcm.metadata.common.utils;

import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

/**
 * @author sunhongfei
 */
public class TestUtils {

    @SneakyThrows
    public static <T> void setFinalFieldValue(String fieldName, T instance, Object value) {
        setFieldValue(instance.getClass(), fieldName, instance, value, true);
    }


    @SneakyThrows
    public static void setStaticFieldValue(Class<?> clazz, String fieldName, Object value) {
        setFieldValue(clazz, fieldName, null, value, false);
    }

    @SneakyThrows
    public static void setStaticFinalFieldValue(Class<?> clazz, String fieldName, Object value) {
        setFieldValue(clazz, fieldName, null, value, true);
    }


    public static <T> void setFieldValue(Class<?> clazz, String fieldName, Object instance, Object value, boolean isFinal) throws NoSuchFieldException, IllegalAccessException {
        Field field = clazz.getDeclaredField(fieldName);
        field.setAccessible(true);

        if (isFinal) {
            Field modifiers = Field.class.getDeclaredField("modifiers");
            modifiers.setAccessible(true);
            modifiers.setInt(field, field.getModifiers() & ~Modifier.FINAL);
        }

        field.set(instance, value);
    }

}
